//
//  PopRootView.m
//  popRootView
//
//  Created by DWE _WODE on 16/9/24.
//  Copyright © 2016年 popRootView. All rights reserved.
//

#import "PopRootView.h"

@interface CTLAction()
@end

@implementation CTLAction
@synthesize titleStr = _titleStr;
@synthesize style = _style;

+ (nonnull instancetype)actionWithTitle:(NSString *)title style:(CTLActionStyle)style handler:(void (^ __nullable)(CTLAction *_Nullable action))handler
{
    return [[[self class]alloc]initWithTitle:title style:style handler:handler];
}

+ (nonnull instancetype)actionWithTitle:(NSString *)title handler:(void (^ __nullable)(CTLAction *_Nullable action))handler
{
    return [[[self class]alloc]initWithTitle:title style:CTLActionStyleDefault handler:handler];
}

- (nonnull instancetype)initWithTitle:(NSString*)title style:(CTLActionStyle)style handler:(void (^ __nullable)(CTLAction *_Nullable action))handler
{
    self = [super init];
    if (self)
    {
        self.aHandler = handler;
        _titleStr = title;
        _style = style;
    }
    return self;
}

@end

#pragma mark - (弹出视图跟组件)DWEPopupRootComponent

@interface PopRootView()

@end

@implementation PopRootView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        CGRect bounds = [UIScreen mainScreen].bounds;
        
        _backgroundView = [[UIView alloc]initWithFrame:bounds];
        _backgroundView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        [self addSubview:_backgroundView];
        
        CGRect frame = (CGRect){0,CGRectGetHeight(bounds),CGRectGetWidth(bounds),0};
        _contentView = [[UIView alloc]initWithFrame:frame];
        _contentView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_contentView];
    }
    return self;
}

- (NSMutableArray*)actionArray
{
    if (_actionArray) {
        return _actionArray;
    }
    _actionArray = [[NSMutableArray alloc]init];
    return _actionArray;
}


- (void)addAction:(CTLAction *)action
{
    if (action) {
        [self.actionArray addObject:action];
    }
}

@end

#pragma mark - DWEAlertComponent

@interface CTLAlertComponent ()

@end

@implementation CTLAlertComponent

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor clearColor];
        
        UIView *barView = [[UIView alloc]init];
        //#3BB4EC
//        barView.backgroundColor = [UIColor colorWithHex:0x3BB4EC];
        barView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:barView];
        
        NSDictionary *bindings = NSDictionaryOfVariableBindings(barView);
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[barView(44)]" options:0 metrics:nil views:bindings]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[barView]-0-|" options:0 metrics:nil views:bindings]];
        
        self.contentView.layer.cornerRadius = 5;
        self.contentView.layer.masksToBounds = YES;
        
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
        _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:_titleLabel];
        
        bindings = NSDictionaryOfVariableBindings(_titleLabel);
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[_titleLabel(24)]" options:0 metrics:nil views:bindings]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_titleLabel]-10-|" options:0 metrics:nil views:bindings]];
        
        _messageLabel = [[UILabel alloc]init];
        _messageLabel.backgroundColor = [UIColor whiteColor];
        _messageLabel.font = [UIFont fontWithName:@"Helvetica" size:16];
        _messageLabel.textColor = [UIColor colorWithRed:0.263 green:0.263 blue:0.263 alpha:1.0];
        _messageLabel.numberOfLines = 0;
        _messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _messageLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:_messageLabel];
        
        bindings = NSDictionaryOfVariableBindings(_messageLabel);
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-54-[_messageLabel]" options:0 metrics:nil views:bindings]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_messageLabel]-10-|" options:0 metrics:nil views:bindings]];
        
        _drawPathLayer = [CAShapeLayer layer];
        _drawPathLayer.lineWidth = 1.0;
        _drawPathLayer.strokeColor = [UIColor colorWithRed:0.898 green:0.898 blue:0.898 alpha:1.0].CGColor;
        _drawPathLayer.fillColor = [UIColor whiteColor].CGColor;
        [self.contentView.layer addSublayer:_drawPathLayer];
    }
    return self;
}

- (void)layoutSubviews
{
    for (UIView *view in self.contentView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    if ([self.actionArray count] <= 0) {
        return;
    }
    
    CGFloat cWidth = CGRectGetWidth(self.contentView.bounds);
    CGFloat cHeight = CGRectGetHeight(self.contentView.bounds);
    
    __weak __typeof(self) ws = self;
    __strong __typeof(ws) ss = ws;
    NSUInteger count = self.actionArray.count;
    CGFloat buttonWidth = cWidth/count;
    CGFloat originY = cHeight - 44;
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, originY-1)];
    [path addLineToPoint:CGPointMake(cWidth, originY-1)];
    
    [self.actionArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj && [obj isKindOfClass:[CTLAction class]]) {
            
            CTLAction *action = (CTLAction*)obj;
            CGRect frame = CGRectMake(idx*buttonWidth, originY, buttonWidth-1, 44);
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = idx;
            button.frame = frame;
            [button setTitleColor:[UIColor colorWithRed:0.404 green:0.404 blue:0.404 alpha:1.0] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
            [button setTitle:action.titleStr forState:UIControlStateNormal];
            [button addTarget:ws action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            [ss.contentView addSubview:button];
            
            if (idx < count - 1 && count > 1) {
                [path moveToPoint:CGPointMake((idx+1)*buttonWidth, originY-1)];
                [path addLineToPoint:CGPointMake((idx+1)*buttonWidth, cHeight)];
            }
        }
    }];
    
    _drawPathLayer.path = path.CGPath;
}

- (void)buttonClick:(UIButton*)sender
{
    if (sender.tag < [self.actionArray count]) {
        
        CTLAction *action = self.actionArray[sender.tag];
        [self dismissWithCompletion:^{
            if (action.aHandler) {
                action.aHandler(action);
            }
        }];
    }
}

#pragma mark --- 显示和隐藏

- (void)show
{
    [self showWithCompletion:nil];
}

- (void)showWithCompletion:(dispatch_block_t)aCompletion
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (window == nil) {
        window = [UIApplication sharedApplication].windows[0];
    }
    [window addSubview:self];
    
    __weak __typeof(self) ws = self;
    __strong __typeof(ws) ss = ws;
    self.contentView.alpha = 1.0;
    self.contentView.transform = CGAffineTransformMakeScale(0.001, 0.001);
    [UIView animateWithDuration:0.2 animations:^{
        ss.contentView.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.25 animations:^{
            ss.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.15 animations:^{
                ss.contentView.transform = CGAffineTransformMakeScale(1, 1);
            } completion:^(BOOL finished) {
                if (aCompletion) {
                    aCompletion();
                }
            }];
        }];
    }];
}

- (void)dismiss
{
    [self dismissWithCompletion:nil];
}

- (void)dismissWithCompletion:(dispatch_block_t)aCompletion
{
    __weak __typeof(self) ws = self;
    __strong __typeof(ws) ss = ws;
    [UIView animateWithDuration:0.2 animations:^{
        ss.contentView.transform = CGAffineTransformMakeScale(1.2, 1.2);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.25 animations:^{
            ss.contentView.transform = CGAffineTransformMakeScale(0.001, 0.001);
            ss.contentView.alpha = 0;
        } completion:^(BOOL finished) {
            if (aCompletion) {
                aCompletion();
            }
            [ws removeFromSuperview];
        }];
    }];
}

@end


#pragma mark - DWESheetComponet

@interface CTLSheetComponet()
@end

@implementation CTLSheetComponet
@synthesize tableView = _tableView;

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
        _titleLabel.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:_titleLabel];
        
        NSDictionary *bindings = NSDictionaryOfVariableBindings(_titleLabel);
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[_titleLabel]" options:0 metrics:nil views:bindings]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_titleLabel]-10-|" options:0 metrics:nil views:bindings]];
        
        _messageLabel = [[UILabel alloc]init];
        _messageLabel.font = [UIFont fontWithName:@"Helvetica" size:15];
        _messageLabel.textAlignment = NSTextAlignmentCenter;
        _messageLabel.numberOfLines = 2;
        _messageLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        _messageLabel.backgroundColor = [UIColor whiteColor];
        _messageLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.contentView addSubview:_messageLabel];
        
        bindings = NSDictionaryOfVariableBindings(_titleLabel,_messageLabel);
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_titleLabel]-5-[_messageLabel]" options:0 metrics:nil views:bindings]];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_messageLabel]-10-|" options:0 metrics:nil views:bindings]];
        
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:_tableView];
        
    }
    return self;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    if ([touch.view isEqual:self.backgroundView]) {
        [self dismissWithCompletion:nil];
    }
}

#pragma mark --- 显示和隐藏

- (void)show
{
    [self showWithCompletion:nil];
}

- (void)showWithCompletion:(dispatch_block_t)aCompletion
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    if (window == nil) {
        window = [UIApplication sharedApplication].windows[0];
    }
    [window addSubview:self];
    NSLog(@"--%@--",NSStringFromSelector(_cmd));
    __weak __typeof(self)ws = self;
    __strong __typeof(ws)ss = ws;
    
    CGRect frame = self.contentView.frame;
    [UIView animateWithDuration:0.35 animations:^{
        
        ss.contentView.transform =  CGAffineTransformMakeTranslation(0,-CGRectGetHeight(frame));
        
    } completion:^(BOOL finished) {
        if (aCompletion) {
            aCompletion();
        }
    }];
}


- (void)dismiss
{
    [self dismissWithCompletion:nil];
}

- (void)dismissWithCompletion:(dispatch_block_t)aCompletion
{
    __weak __typeof(self)ws = self;
    __strong __typeof(ws)ss = ws;
    [UIView animateWithDuration:0.35 animations:^{
        ss.contentView.transform =  CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        ss.alpha = 0.0;
        if (aCompletion) {
            aCompletion();
        }
        [ws removeFromSuperview];
    }];
}

@end
